//
//  HSWebViewController.swift
//  33web
//
//  Created by 宋海胜 on 2020/11/25.
//

import UIKit
import WebKit
import SwiftWeb
import MapKit

import RxSwift
import RxAlamofire
import HandyJSON


enum JsMethod {
    case passGPSInfo
    case passVersion
    case passVoiceContent
    case passPayResult
    case passStatusType
}

// 自定义编辑
class HSWebViewController: BaseWebViewController, XYVoiceRecognizeProtocol {
    
    fileprivate var isLoginPage: Bool = false
    fileprivate var location = LocationManager()
    fileprivate var isOnece = false
    fileprivate var configManager = Tool()
    fileprivate var backImgView = UIImageView()
    fileprivate var urlInputView: InputView!
    fileprivate var apiInputView: APIInputView!
    fileprivate var voiceView: XYVoiceRecognizeManager?
    //    internal var liveView = ZGLiveView()
    public var canAllButUpsideDown = false
    let disposeBag = DisposeBag()
    var statusBgView: UIView = {
        let v = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: kStatusBarHeight))
        v.isHidden = true
        return v
    }()
    
    deinit {
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "getGPSInfo")
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "saveUnreadMsgCnt")
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "getVersion")
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "passVideoParams")
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "leaveVideoPage")
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "startVoice")
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "stopVoice")
        
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "toMiniProgram")
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "toGaodeApp")
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "toPay")
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "toShare")
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "toDownLoad")
        
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "toHomepage")
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "webGoBack")
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "webShangyiji")
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "loginOut")
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "changeRole")
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "callSomeOne")
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "statusBarColor")
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "statusBarHide")
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "getStatusType")
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.isHidden = true
        self.tabBarController?.tabBar.isHidden = true
    }
    
    init(path: String, isLoginPage: Bool = false) {
        super.init(path: path)
        self.isLoginPage = isLoginPage
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        progressView.tintColor = .blue
        
        // 萤石云视频全屏
        //        liveView.currentVC = self
        //        liveView.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight)
        
        // 启动图复制图片、web未加载完成时覆盖页面
        self.backImgView = self.configManager.getLanuchboardImage()
        self.backImgView.frame = self.view.bounds
        self.view.addSubview(self.backImgView)
        self.view.addSubview(self.statusBgView)
        // 顶部状态栏高度问题解决
        self.configManager.topMangain(webView: webView, vc: self)
        
        // 网络判断，重新加载网页
        judgeNetwork()
        // 经纬度
        location.locationProtocol = self
        
        // 语音听写、播报
        self.voiceView = XYVoiceRecognizeManager(currentVC: self)
        self.voiceView!.delegate = self
        
        #if DEBUG // 判断是否在测试环境下
        // 输入框
        if isLoginPage {
            
            urlInputView = InputView(frame: CGRect(x: 0, y: STATUSBAR_HEIGHT + 100, width: kScreenWidth, height: 50), currentVC: self)
            view.addSubview(urlInputView)
            apiInputView = APIInputView(frame: CGRect(x: 0, y: STATUSBAR_HEIGHT + 150, width: kScreenWidth, height: 50), currentVC: self)
            view.addSubview(apiInputView)
        }
        #else
        
        #endif
        
        //        VersionCheck.hasUpdateVersion(self, disposeBag)
    }
    
    override func injectSwiftMethod(_ config: WKWebViewConfiguration) {
        config.userContentController.add(WeakScriptMessageDelegate(scriptDelegate: self), name: "getGPSInfo")
        config.userContentController.add(WeakScriptMessageDelegate(scriptDelegate: self), name: "saveUnreadMsgCnt")
        config.userContentController.add(WeakScriptMessageDelegate(scriptDelegate: self), name: "getVersion")
        config.userContentController.add(WeakScriptMessageDelegate(scriptDelegate: self), name: "passVideoParams")
        config.userContentController.add(WeakScriptMessageDelegate(scriptDelegate: self), name: "leaveVideoPage")
        config.userContentController.add(WeakScriptMessageDelegate(scriptDelegate: self), name: "startVoice")
        config.userContentController.add(WeakScriptMessageDelegate(scriptDelegate: self), name: "stopVoice")
        
        config.userContentController.add(WeakScriptMessageDelegate(scriptDelegate: self), name: "toMiniProgram")
        config.userContentController.add(WeakScriptMessageDelegate(scriptDelegate: self), name: "toGaodeApp")
        config.userContentController.add(WeakScriptMessageDelegate(scriptDelegate: self), name: "toPay")
        config.userContentController.add(WeakScriptMessageDelegate(scriptDelegate: self), name: "toShare")
        config.userContentController.add(WeakScriptMessageDelegate(scriptDelegate: self), name: "toDownLoad")
        
        config.userContentController.add(WeakScriptMessageDelegate(scriptDelegate: self), name: "toHomepage")
        config.userContentController.add(WeakScriptMessageDelegate(scriptDelegate: self), name: "webGoBack")
        config.userContentController.add(WeakScriptMessageDelegate(scriptDelegate: self), name: "webShangyiji")
        config.userContentController.add(WeakScriptMessageDelegate(scriptDelegate: self), name: "loginOut")
        config.userContentController.add(WeakScriptMessageDelegate(scriptDelegate: self), name: "changeRole")
        config.userContentController.add(WeakScriptMessageDelegate(scriptDelegate: self), name: "callSomeOne")
        config.userContentController.add(WeakScriptMessageDelegate(scriptDelegate: self), name: "statusBarColor")
        config.userContentController.add(WeakScriptMessageDelegate(scriptDelegate: self), name: "statusBarHide")
        config.userContentController.add(WeakScriptMessageDelegate(scriptDelegate: self), name: "getStatusType")
    }
    
    override func jsAction() {
        
    }
    
    // 在viewDidLoad中模态不行，此时页面还没加载完成
    fileprivate func judgeNetwork() {
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
            
            if self.configManager.judgeNetworkState(self) {
                self.loadWeb()
            }
        }
    }
    
    fileprivate func jsAction(param: String, type: JsMethod) {
        
        var javascript: String = ""
        
        switch type {
        
        case .passGPSInfo:
            javascript = "javascript:passGPSInfo(\"\(param)\")"
            
        case .passVersion:
            javascript = "javascript:passVersion(\"\(param)\")"
            
        case .passVoiceContent:
            javascript = "javascript:passVoiceContent(\"\(param)\")"
            
        case .passPayResult:
            javascript = "javascript:payResult(\"\(param)\")"
            
        case .passStatusType:
            javascript = "javascript:passStatusType(\"\(param)\")"
        }
        self.webView.evaluateJavaScript(javascript) { (res, error) in
            print("swift向js传值\n  param: \(param)\n  response: \(res ?? "nil")\n  error: \(error?.localizedDescription ?? "nil")")
        }
    }
    
    override func swiftAction(_ name: String, _ body: Dictionary<String, Any>) {
        
        switch name {
        
        case "getGPSInfo":
            gpsService()
            
        case "saveUnreadMsgCnt":
            let num = body["notReadNum"] as! NSNumber
            UIApplication.shared.applicationIconBadgeNumber = num.intValue > 99 ? 99 : num.intValue
            
        case "getVersion":
            let infoDic = Bundle.main.infoDictionary
            let appVersion = infoDic!["CFBundleShortVersionString"] as! String
            jsAction(param: appVersion, type: .passVersion)
            
        //        case "passVideoParams":
        //            setVideoPage(body)
        
        //        case "leaveVideoPage":
        //            liveView.leaveVideoPage()
        
        case "startVoice":
            print(name, "+", body)
            self.voiceView!.startIFlySpeechRecognize()
            
        case "stopVoice":
            self.voiceView!.stopIFlySpeechRecognize()
            
        case "toMiniProgram":
            let appId = body["appId"] as? String ?? ""
            let path = body["path"] as? String ?? ""
            WXManager.toMiniProgram(appId, path, self)
            
        case "toGaodeApp":
            Tool.routePlanning(body)
            
        case "toPay":
            Utils.toPay(body)
            
        case "toShare":
            XYShareManger.toShare(body, self)
            
        case "toDownLoad":
            let url = body["url"] as? String ?? ""
            UIApplication.shared.open(URL(string: url)!, options: [:], completionHandler: nil)
            
        case "callSomeOne":
            let phoneNum = body["phoneNum"] as? String ?? ""
            self.configManager.callSomeOne(phoneNum)
            
        case "toHomepage":
            let token = body["token"] as? String ?? ""
            let roleId: String? = body["roleId"] as? String
            let jwt = body["jwt"] as? String ?? ""
            self.view.makeToast("jwt: \(jwt)")
            UserDefaults.standard.setValue(token, forKey: "token")
            UserDefaults.standard.setValue(roleId, forKey: "roleId")
            UserDefaults.standard.setValue(jwt, forKey: "jwt")
            if let vc = UIApplication.shared.keyWindow?.rootViewController, vc.isKind(of: SYBaseTarBarViewController.self) {
                self.dismiss(animated: true, completion: nil)
            } else {
                let tabbarVC = SYBaseTarBarViewController(roleId: roleId)
                UIApplication.shared.keyWindow?.rootViewController = tabbarVC
            }
            
        case "webGoBack":
            self.sy_popVC()
            
        case "webShangyiji":
            
            webView.goBack()
            
        case "loginOut":
            UserDefaults.standard.removeObject(forKey: "token")
            UserDefaults.standard.removeObject(forKey: "roleId")
            UserDefaults.standard.removeObject(forKey: "jwt")
            
            let loginVC = HSWebViewController(path: kWebUrl, isLoginPage: true)
            UIApplication.shared.keyWindow?.rootViewController = loginVC
            
        case "changeRole":
            let token = body["token"] as? String ?? ""
            let roleId: String? = body["roleId"] as? String
            let jwt = body["jwt"] as? String ?? ""
            self.view.makeToast("jwt: \(jwt)")
            UserDefaults.standard.setValue(token, forKey: "token")
            UserDefaults.standard.setValue(roleId, forKey: "roleId")
            UserDefaults.standard.setValue(jwt, forKey: "jwt")
            
            let tabbarVC = SYBaseTarBarViewController(roleId: roleId)
            UIApplication.shared.keyWindow?.rootViewController = tabbarVC
        case "statusBarColor":
            let barColor = body["barColor"] as? String ?? ""
            self.webView.frame = CGRect(x: 0, y: kStatusBarHeight, width: kScreenWidth, height: kScreenHeight)
            statusBgView.backgroundColor = UIColor.hexString(hex: barColor)
            statusBgView.isHidden = false
            
        case "statusBarHide":
            self.webView.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight)
            statusBgView.backgroundColor = .white
            statusBgView.isHidden = true
        case "getStatusType":
            jsAction(param: isPhoneX ? "isIphoneX" : "notIphoneX", type: .passStatusType)
        default:
            break
        }
    }
    
    override func getH5Url(_ url: String) {
        
        if (url.contains("tel://")) {
            let phoneUrl = url.components(separatedBy: "tel://").last
            self.configManager.callSomeOne(phoneUrl!)
        }
    }
    
    override func loadSuccess() {
        
        UIView.animate(withDuration: 0.3, delay: 0.1, options: .curveEaseInOut, animations: {
            self.backImgView.alpha = 0
        }) { (finish) in
            self.backImgView.isHidden = true
        }
    }
    
    override func loadFail() {
        backImgView.isHidden = false
        self.configManager.alertToReload(self) {
            self.loadWeb()
        }
    }
    
    // 定位
    fileprivate func gpsService() {
        
        //只获取一次
        isOnece = true
        self.location.startLocation()
    }
    
    //    open override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    
    //        if size.width > size.height {// 横屏
    //            liveView.blanner!.frame = CGRect(x: 0, y: 0, width: kScreenHeight, height: kScreenWidth)
    //            liveView.showView(isFullScreen: true)
    //        } else {
    //            liveView.blanner!.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenWidth*9/16)
    //            liveView.hideAboveViews()
    //            self.view.hideToastActivity()
    //            liveView.showView(isFullScreen: false)
    //        }
    //    }
    
    //    func setVideoPage(_ params: Dictionary<String, Any>) {
    //        if liveView.player != nil {
    //            self.liveView.fullScreenAction()
    //            return
    //        }
    //        Tool.requestAuthorizationPhotoLibary()
    //        Tool.requestMicroPhoneAuth()
    //        self.canAllButUpsideDown = true
    //        self.liveView.configureSDK(params)
    //        self.liveView.fullScreenAction()
    //    }
    
    func voiceContent(content: String) {
        self.jsAction(param: content, type: .passVoiceContent)
    }
    
    func payResult() {
        self.jsAction(param: "", type: .passPayResult)
    }
}

extension HSWebViewController: LocationProtocol {
    
    func getGPSAuthorizationFailure() {
        let alert = UIAlertController(title: "提示", message: "请打开定位，以便获取您的位置信息", preferredStyle: .alert)
        
        let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
        alert.addAction(okAction)
        
        self.present(alert, animated: true, completion: nil)
    }
    
    func getGPSSuccess(latitude: Double, longitude: Double) {
        location.stopLocation()
        if (self.isOnece) {
            print("lng: \(longitude) lat: \(latitude)")
            let param = "\(longitude),\(latitude)"
            self.jsAction(param: param, type: .passGPSInfo)
            self.isOnece = false
        }
    }
    
    func getGPSFailure(error: Error) {
        self.isOnece = false
        print("getMoLocation error: \(error.localizedDescription)")
        if (!self.isOnece) {
            location.stopLocation()
        }
    }
    
    func getLocationSuccess(_ area: String, _ locality: String, _ subLocality: String, _ thoroughfare: String, _ name: String) {
        print(area,locality,subLocality,thoroughfare,name)
    }
}
